import {
  getVerifyCode,
  getPhoneNumber,
  handleWXRegister,
  handleRegister,
} from '../../api/user'

import {
  setToken
} from '../../utils/storage'

import {
  wxLogin,
  authUser,
} from '../../api/login'
import {
  toDefaultPage
} from '../../utils/navigate'
let timer = null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    code: '',
    profile: false,
    openId: '',
    inRemainTime: false,
    remainTime: 60,
    wxPhone: '',
    phone: '',
    pwd: '',
    verifyCode: '',
    inviteKey: '',
    userSource: '',
    verifyInfo: {
      codeId: '',
      code: '',
      ext: ''
    },
    back: true,
    enter_by_invite: false,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (getApp().globalData.profile) {
      this.setData({
        profile: true
      })
      this.wxLogin()
    }
    this.setData({
      back: getCurrentPages().length > 1
    })
    if (options.share_invite_key) {
      this.setData({
        inviteKey: options.share_invite_key,
        openId: getApp().globalData.openId,
        enter_by_invite: true,
        userSource: options.user_source || ''
      })
    }
    if (options.scene) {
      this.setData({
        inviteKey: options.scene,
        enter_by_invite: true,
      })

    }
    console.log('regist onLoad', this.data);
  },
  async wxLogin() {
    wx.showLoading('...')
    const {
      code
    } = await wxLogin();
    this.setData({
      code: code
    })

    wx.hideLoading()
  },
  async getPhoneByWx(e) {
    let {
      openId
    } = getApp().globalData
    let {
      iv,
      encryptedData
    } = e.detail
    try {
      let result = await getPhoneNumber({
        openId,
        iv,
        encryptedData
      })
      if (result.phone) {
        this.setData({
          wxPhone: result.phone
        })
      } else {
        wx.showToast({
          title: '获取手机号失败！',
          icon: 'none'
        })
      }

    } catch (error) {
      wx.showToast({
        title: '获取手机号失败！',
        icon: 'none'
      })
    }


  },

  async getCode() {
    if (timer) {
      return;
    }


    if (!this.data.phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }

    try {
      let result = await getVerifyCode({
        phonenumber: this.data.phone
      })

      wx.showToast({
        title: result.msg,
        icon: 'none'
      })
      if (result.data) {
        this.setData({
          verifyInfo: {
            code: result.data.code,
            codeId: result.data.codeId,
            ext: result.data.ext,
          }
        })
        this.setData({
          inRemainTime: true,
          remainTime: 60
        })
      } else {
        wx.showToast({
          title: result.msg,
          icon: 'none'
        })
        return;
      }

      const the_timer = setInterval(() => {

        if (this.data.remainTime === 0) {
          timer = null;
          this.setData({
            inRemainTime: false,
            remainTime: 0,
          })
          clearInterval(timer)
        } else {
          const count = this.data.remainTime - 1
          this.setData({
            // inRemainTime: true,
            remainTime: count
          })
        }
      }, 1000);

      timer = the_timer
    } catch (error) {

      wx.showToast({
        title: '获取验证码失败',
        icon: 'none'
      })
    }
  },

  phoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  pwdInput(e) {
    this.setData({
      pwd: e.detail.value
    })
  },
  inviteKeyInput(e) {
    this.setData({
      inviteKey: e.detail.value
    })
  },

  verifyCodeInput(e) {
    this.setData({
      verifyCode: e.detail.value
    })
  },
  validForm() {
    if (!(/^[1][0-9][0-9]{9}$/.test(this.data.phone))) {
      wx.showToast({
        title: "请输入合法的手机号",
        icon: 'none'
      })
      return;
    }
    if (!(/^[a-zA-Z0-9~!@#$%^&*()_+`\-={}:";'<>?,.\/]{6,14}$/.test(this.data.pwd))) {
      wx.showToast({
        title: "请输入6-14位密码",
        icon: 'none'
      })
      return;
    }
    if (!this.data.phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }

    if (!this.data.pwd) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      return
    }

    if (!this.data.inviteKey) {
      wx.showToast({
        title: '请输入邀请码',
        icon: 'none'
      })
      return
    }

    if (!this.data.verifyCode) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none'
      })
      return
    }
    if (!this.data.verifyInfo.code || !this.data.verifyInfo.codeId || !this.data.verifyInfo.ext) {
      wx.showToast({
        title: '验证码信息有误',
        icon: 'none'
      })
      return
    }
    return true;
  },
  bindPhone() {
    if (!this.validForm()) {
      return;
    }
    const params = {
      phonenumber: this.data.phone,
      invite_key: this.data.inviteKey,
      passwd: this.data.pwd,
      code: this.data.verifyCode,
      id: this.data.verifyInfo.codeId,
      wx_openid_xin: this.data.openId,
      token: this.data.verifyInfo.ext,
      userSource: this.data.userSource
    }
    //TODO 完善
    handleRegister(params)
      .then(res => {
        if (res.token && res.code !== "500") {
          setToken(res.token)
          wx.showToast({
            title: '注册成功',
            icon: 'none'
          });
          if (this.data.userSource === '5') {
            wx.navigateTo({
              url: '/pages/identification/identification?conditionOfUserSource5=1'
            });
          } else {
            toDefaultPage()
          }
        } else {
          wx.showToast({
            title: res.errMsg,
            icon: 'none'
          })

        }

      })
      .catch(err => {

        wx.showToast({
          title: '注册失败',
          icon: 'none'
        })
      })


  },

  bindWxPhone() {
    if (!this.data.pwd) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      return
    }

    if (!this.data.inviteKey) {
      wx.showToast({
        title: '请输入邀请码',
        icon: 'none'
      })
      return
    }

    const params = {
      phone: this.data.wxPhone,
      invite_key: this.data.inviteKey,
      password: this.data.pwd
    }
    handleWXRegister(params)
      .then(res => {

        //TODO 完善
        if (false) {
          setToken(res.data.token)
        }
        wx.showToast({
          title: '绑定手机号成功',
          icon: 'none'
        })
      })
      .catch(err => {

        wx.showToast({
          title: '绑定手机号失败',
          icon: 'none'
        })
      })
  },

  toLogin() {
    wx.redirectTo({
      url: '/pages/signin/signin'
    })
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  async toWXLogin() {
    //开始登陆
    if (!this.validForm()) {
      return;
    }
    try {
      wx.showLoading('登陆中...')
      const {
        code
      } = await wxLogin();
      const loginParams = {
        code
      }
      let authInfo = await authUser(loginParams)
      const {
        globalData
      } = getApp()
      wx.hideLoading()
      if (authInfo.token == '0') {
        //没有绑定手机号 去注册页面
        //缓存openid
        globalData.openId = authInfo.wx_openid
        this.setData({
          openId: authInfo.wx_openid
        })
        wx.setStorageSync('openId', authInfo.wx_openid);
        this.bindPhone();
      } else {
        // 由于流程 所以前面有条件判断， 绑定微信号的用户一般不会走到这一步
        wx.showToast({
          title: '微信号已绑定手机号，请直接登录',
          icon: 'none'
        })
      }
    } catch (error) {

      wx.showToast({
        title: '登陆失败',
        icon: 'none'
      })
    }
  }
})